<template>
  <div class="container" :style="{'background': resData.backgroundColor }">
    <header-nav :dataInfo="resData" @headerNavHeight="headerNavHeight" :showNav="showNav"></header-nav>
    <div class="module-box">
      <!-- <second-page :content="detailsList" :enterpriceId="memberEnterpriseId" urlFrom="home"></second-page> -->
      <custom-page :content="detailsList" @categoryLink="categoryLink"></custom-page>
      <div class="fixed-box" style="min-height: 600px;" v-if="!categoryNoData">
        <fixed-component 
          :categoryList="categoryList" 
          :goodsList="goodsList" 
          :top="headNavHeight"
          @onChange="categoryChange" 
          @categoryAction="categoryAction"
          :categoryActiveId="categoryId"></fixed-component>
        <div class="nodata" v-if="nodata">
          <div class="align-c" style="padding-top: 80px">
            <img v-if="fileSpace" :src="fileSpace + '/images/anchor-nodata.png'" class="width-205 height-173" alt="">
            <div class="align-c mar-t-5 font-16 font-color-9">
              暂无数据
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import headerNav from '@/components/headerNav'
import GetUserInfo from '@/components/GetUserInfo'
import RegisterBar from '@/components/RegisterBar'
import { getMemberInfo, getCustomPage, listAllCategory, pagingMyProjectGoods } from '@/api/home'
import { listShopBannerByMemberId } from '@/api/shop'
import { checkLogin, getAuth } from '@/api/login'
import { getAppInfo } from '@/api/common'
import { setAnchorType, setCategoryInfo, setNickName, setAppInfo, setCustomerId, setRoleType } from '@/utils/auth'
import CustomPage from '@/components/CustomPage/index'
import FixedComponent from '../components/FixedComponent/index.vue'

export default {
  components: { GetUserInfo, headerNav, RegisterBar, CustomPage, FixedComponent },
  data() {
    return {
      memberInfo: {},
      resData: {},
      detailsList: [],
      detailsNone: false,
      isGetUserInfo: false,
      showPhonePage: '0',
      registerBoolean: false,
      getEnterpriseId: '',
      getDefaultMemberId: '',
      categoryList: [],
      goodsList: [],
      params: {},
      currentPage: 1,
      categoryParams: {},
      nodata: false,
      categoryNoData: false,
      categoryId: '',
      pullLoad: {
        finished: false,
        loading: false
      },
      appInfo: {},
      headNavHeight: 0,
      skeletonLoading: true,
      linkList: {
        1001: '/pages/personal/coupon/coupon-center/main', // 领券中心
        1002: '/pages/contact-btn/main', // 微信客服
        1004: '/pages/shop/main', // 分类链接
        1005: '/pages/home/main', // 首页
        1006: '/pages/shop/main', // 分类
        1007: '/pages/shop/cart/main', // 购物车
        1008: '/pages/personal/main', // 个人中心
        1009: '/pages/home/content-center/main', // 内容中心
        1010: '/pages/shop/searchView/main', // 搜索页面
        1101: '/pages/home/second-custom/main', // 自定义页面
        1401: '/pages/home/live-list/main', // 直播列表
        1501: '/pages/home/default-seckill/main', // 限时秒杀
        1502: '/pages/home/default-seckill/main', // 社区团购
        2001: '/pages/shop/detail/main', // 商品详情
        4001: '/pages/home/content-center/content-detail/main' // 内容中心详情
      },
      memberEnterpriseId: '',
      getAppInfo: {}
    }
  },
  onLoad() {
    this.memberInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
  },
  onShow() {
    this.initEls()
  },
  mounted() {
    this.getCustomPage()
    this.listAllCategory()
    this.$nextTick(() => {
      let query = this.$pt.createSelectorQuery().selectAll('.top-name-bar')
      query.boundingClientRect(rects => {
        let rect = rects[0]
        this.headNavHeight = rect.height
      }).exec()
    })
    setTimeout(() => {
      this.initEls()
    }, 100)
  },
  // 下拉刷新
  onPullDownRefresh() {
    Object.assign(this.$data, this.$options.data())
    this.$nextTick(() => {
      let query = this.$pt.createSelectorQuery().selectAll('.top-name-bar')
      query.boundingClientRect(rects => {
        let rect = rects[0]
        this.headNavHeight = rect.height
      }).exec()
    })
    this.initEls()
    this.skeletonLoading = true
    this.getCustomPage()
    this.listAllCategory()
    setTimeout(() => {
      this.$pt.stopPullDownRefresh()
    }, 500)
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished && !this.categoryNoData && this.getShowBuyCard) {
      setTimeout(() => {
        this.pagingMyProjectGoods(this.categoryParams)
      }, 300)
    }
  },
  methods: {
    showTabBar() {
      this.$pt.showTabBar({
        animation: false
      })
    },
    getAppInfoEls() {
      getAppInfo().then((response) => {
        if (response.isError) return
        this.appInfo = response.data
        setAppInfo(this.appInfo)
        if (this.appInfo.enterpriseId) {
          this.getEnterpriseId = this.appInfo.enterpriseId
          this.getDefaultMemberId = this.appInfo.defaultMemberId
          this.getCustomPage()
          this.listAllCategory()
        }
      }).catch(() => {
      })
    },
    initEls() {
      this.showNav = false
      this.params = {}
      this.spaceBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44
      this.params = JSON.parse(this.getCurrentPage().query.params)
      // this.getAppEls()
      // this.getMemberInfo()
      if (this.getCustomerId) {
        this.initCustomerInfo()
      } else {
        checkLogin()
        setTimeout(() => {
          this.authEls()
        }, 500)
        this.$pt.setStorageSync('homeNone', true)
      }
    },
    authEls() {
      let that = this
      this.$pt.login({
        success(res) {
          if (res.code) {
            getAuth(res.code).then((response) => {
              if (response.data.customerId) {
                setCustomerId(response.data.customerId)
                that.initCustomerInfo()
              } else {
                that.registerBoolean = true
              }
            }).catch(() => {
            })
          }
        }
      })
    },
    userPhoneLayer(scanIn) {
      if (!this.getCustomerId && scanIn) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetUserInfo = false
        setTimeout(() => {
          this.isGetUserInfo = true
        }, 100)
      }
      if (!this.$pt.getStorageSync('phone') && (scanIn || this.showPhonePage === '1')) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetPhoneInfo = false
        setTimeout(() => {
          this.isGetPhoneInfo = true
        }, 100)
      }
      if (this.$pt.getStorageSync('phone') && scanIn) {
        this.$pt.showTabBar({
          animation: false
        })
        this.isGetPhoneInfo = false
      }
      if (!this.getCustomerId && scanIn) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetUserInfo = false
        setTimeout(() => {
          this.isGetUserInfo = true
        }, 100)
      }
    },
    initMemberInfo() {
      this.initCustomerInfo()
      this.getCustomPage()
      this.listAllCategory()
      // 如果缓存没有手机号码，则弹出微信授权手机号码
      const scanIn = this.$pt.getStorageSync('scanIn')
      const scanCode = this.$pt.getStorageSync('scanCode')
      if (this.getCustomerId && this.getPhone && scanIn && scanCode) {
        this.$pt.showTabBar({
          animation: false
        })
        setTimeout(() => {
          this.$pt.reLaunch({
            url: '/pages/home/get-card/main?salesData=' + scanCode
          })
        }, 300)
        return
      }
      this.userPhoneLayer(scanIn)
    },
    // 会员基本信息
    initCustomerInfo() {
      if (this.getRoleType === 2) return
      getMemberInfo(this.getCustomerId).then((response) => {
        if (response.isError) return
        this.customerInfo = response.data
        setNickName(this.customerInfo.nickname)
        if (this.customerInfo.anchorAuthority !== undefined) {
          setAnchorType(this.customerInfo.anchorAuthority)
        }
        if (this.customerInfo.anchorAuthority) {
          setRoleType(1)
          this.registerBoolean = false
        } else {
          this.registerBoolean = true
        }
      }).catch(() => {
      })
    },
    // 获取商品分类
    listAllCategory() {
      console.log('listAllCategory')
      // 初次获取不到企业ID和默认memberId时，先调用getAppInfoEls获取
      if (!this.getEnterpriseId) {
        this.getAppInfoEls()
        return
      }
      this.categoryNoData = false
      listAllCategory(this.getEnterpriseId).then(response => {
        if (response.isError) return
        if (response.data.length === 0) {
          this.categoryNoData = true
        }
        this.categoryList = response.data
        this.categoryList.unshift({
          categoryId: '',
          categoryName: '全部',
          enterpriseCategoryId: ''
        })
        this.categoryParams.categoryActive = this.categoryList[0].enterpriseCategoryId
        this.categoryParams.createTimeSort = 1
        this.nodata = false
        this.pagingMyProjectGoods(this.categoryParams)
      }).catch(() => {
      })
    },
    // 获取分类商品
    pagingMyProjectGoods(categoryParams) {
      console.log('pagingMyProjectGoods')
      let params = {
        categoryId: categoryParams.categoryActive,
        size: 10,
        currentPage: this.currentPage,
        memberId: this.getCustomerId,
        customerId: this.getCustomerId,
        enterpriseId: this.getEnterpriseId,
        createTimeSort: categoryParams.createTimeSort || '', // 新品排序
        salesNumSort: categoryParams.salesNumSort || '', // 销售排序
        anchorRatioSort: categoryParams.anchorRatioSort || '' // 佣金排序
      }
      console.log(params)
      return pagingMyProjectGoods(params).then(response => {
        if (response.isError) return
        if (response.data.total === 0) {
          this.nodata = true
          this.pullLoad.finished = true
          return
        }
        response.data.records.forEach(item => {
          // 网红在卖人数
          item.anchorSalePeople = item.putawayNum + item.virtualPutawayNum
          this.goodsList.push(item)
        })
        this.currentPage++
        if (this.goodsList.length === 0 || this.goodsList.length >= response.data.total) {
          this.pullLoad.finished = true
        }
        // return true
      }).catch(() => {
      })
    },
    // 监听固定组件区域筛选发生变化
    categoryChange(params) {
      this.categoryParams = params
      this.goodsList = []
      this.currentPage = 1
      this.nodata = false
      this.pullLoad.finished = false
      this.pagingMyProjectGoods(this.categoryParams)
    },
    categoryAction(categoryId) {
      this.categoryId = categoryId
    },
    // 自定义组件分类链接
    async categoryLink(item) {
      this.categoryId = item.categoryId
      this.categoryParams.categoryActive = item.categoryId
      this.goodsList = []
      this.currentPage = 1
      this.nodata = false
      this.pullLoad.finished = false
      await this.pagingMyProjectGoods(this.categoryParams)
      // 监听固定组件在屏幕的位置
      this.$pt.pageScrollTo({ selector: '.fixed-box' })
    },
    linkTo(item) {
      if (item.linkType) {
        const linkType = Number(item.linkType)
        if (item.linkStatus === 0) {
          this.$utils.showToast({title: '链接已失效'})
          return
        }
        if (linkType === 1002) return
        if (linkType === 1004) {
          this.$pt.removeStorageSync('categoryInfo')
          setCategoryInfo(this.$utils.getCaption(item.linkParams))
          this.$pt.switchTab({url: this.linkList[item.linkType]})
          return
        }
        if (linkType === 1005 || linkType === 1006 || linkType === 1007 || linkType === 1008) {
          this.$pt.switchTab({ url: this.linkList[item.linkType] })
          return
        }
        if (item.linkParams) {
          this.$pt.navigateTo({url: this.linkList[item.linkType] + item.linkParams})
        } else {
          if (linkType === 1501 || linkType === 1502) {
            this.$pt.navigateTo({url: this.linkList[item.linkType] + '?enterpriseId=' + this.memberEnterpriseId + '&linkType=' + linkType})
          } else {
            this.$pt.navigateTo({url: this.linkList[item.linkType]})
          }
        }
      }
    },
    initListBanner() {
      listShopBannerByMemberId(this.getMemberId).then((response) => {
        if (response.isError) return
        this.listBanner = []
        response.data.forEach((banner) => {
          this.listBanner.push({ imgUrl: banner.imageUrl })
        })
        if (this.listBanner.length === 0) {
          // 默认banner
          this.listBanner.push({ imgUrl: this.fileSpace + '/images/1-1-banner6.jpg' })
        }
      }).catch(() => {
      })
    },
    getCustomPage() {
      this.$utils.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 3000
      })
      this.resData = {}
      this.detailsList = []
      let params = {
        pageId: this.params.pageId,
        memberId: this.getMemberId,
        customerId: this.getCustomerId,
        enterpriseId: this.getEnterpriseId ? this.getEnterpriseId : '',
        roleType: this.getRoleType ? this.getRoleType : ''
      }
      if (!this.getCustomerId) return
      getCustomPage(params).then(response => {
        if (response.isError) return
        this.$pt.hideToast()
        if (Object.keys(response.data).length !== 0) {
          this.resData = response.data
          if (this.resData.titleType === 11) {
            this.$pt.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: this.resData.titleBackgroundColor
            })
          } else {
            this.$pt.setNavigationBarColor({
              frontColor: '#000000',
              backgroundColor: this.resData.titleBackgroundColor
            })
          }
          if (response.data.detailsList) {
            this.detailsList = response.data.detailsList
          }
          if (this.params.pageType === 10) {
            let swiperInclude = 0
            if (response.data.swiperList) {
              if (response.data.swiperList.length > 0) {
                swiperInclude = 1
                this.listBanner = response.data.swiperList
              }
            }
            if (!swiperInclude) {
              // this.initListBanner()
            }
          }
        } else {
          this.$pt.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff'
          })
          if (this.pageId === 1) {
            // this.initListBanner()
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.contactBtn {
  background-color: transparent!important;
  position: absolute;
  width:100%;
  height:100%;
  left: 0;
  top: 0;
  z-index: 999;
  border-color: transparent!important;
  border: none!important;
}
.top-swiper {
  width: 375px;
  height: 158px;
}
.top-img {
  width: 375px;
  height: 158px;
}
.module-box{  
  .title-bar{
    h2{
      margin: 0;
      padding: 0;
    }
  }
  .timer{
    .timer-t{
      color: #818181;
    }
  }
  ul{
    padding: 0;
    margin: 0; 
    &:after{
      content: '';
      display: block;
      clear: both;
      font-size: 0;
    }       
    &.show-type-1{
      li{
        &:last-child{
          margin-bottom: 0;
        }
        .detail-box{
          padding: 12px 12px 8px 12px;
        }
        .gooods-pic{
          img{
            width: 100%;
            height: 190px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
          }
          &.pos-rel{
            &.del-show{
              .del-layer-bg{
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
              }
              .del-layer{
                &.stock-none{
                  label{
                    margin-top: 12%;
                  }
                }
                label{
                  width: 100px;
                  height: 100px;
                  line-height: 100px;
                  font-size: 24px;
                  margin-top: 8%;
                }
                p{
                  font-size: 15px;
                  margin-top: 3%;
                }
              }
            }
          }
        }
      }
    }
    &.show-type-2{
      li{
        width: 48%;
        float: left;
        &:nth-child(odd){
          margin-right: 4%;
        }
        .detail-box{
          padding: 8px 10px 5px 10px;
        }
        .desc{
          margin-bottom: 8px!important;
        }
        .gooods-pic{
          img{
            width: 100%;
            height: 160px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
          }
          &.pos-rel{
            &.del-show{
              .del-layer-bg{
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
              }
              .del-layer{
                &.stock-none{
                  label{
                    margin-top: 26%;
                  }
                }
                label{
                  width: 70px;
                  height: 70px;
                  line-height: 70px;
                  font-size: 16px;
                  margin-top: 18%;
                }
                p{
                  font-size: 12px;
                  margin-top: 6%;
                }
              }
            }
          }
        }
        .buy-now-type{
          display: none;
        }
        .height-s-item{
          height: 19px;
          margin-bottom: -1px; 
        }
        .price{
          .label-s{
            display: none;              
          }
        }
        button.remove-type{
          font-size: 10px;
          padding: 4px 6px;
          margin-right: -4px;
        }
        .info-bar{
          .remove-type{
            display: none!important;
          }
        }
        .line-item.remove-type{
          display: inline-block!important;
        }
        .last-item.remove-type{
          display: none!important;
        }
      }
    }
    &.show-type-3{
      li{
        display: -webkit-box;
        display: -webkit-flex;
        display: flex;
        flex-flow: row;
        align-items: center;
        padding: 10px 10px;
        &:last-child{
          margin-bottom: 0;
        }
        .pic-box{
          margin-right: 6px;
          .gooods-pic{
            img{
              width: 100px;
              height: 100px;
            }
            &.pos-rel{
              &.del-show{
                .del-layer{
                  &.stock-none{
                    label{
                      margin-top: 22%;
                    }
                  }
                  label{
                    width: 50px;
                    height: 50px;
                    line-height: 50px;
                    margin-top: 14%;
                    font-size: 13px;
                  }
                  p{
                    font-size: 10px;
                    margin-top: 5%;
                  }
                }
              }
            }
          }
        }
        .detail-box{
          padding: 0px 2px 0px 7px;
          -webkit-box-flex: 1;
          -webkit-flex: 1;
          flex: 1;
        }
        .tag{
          span{
            padding: 1px 5px!important;
          }
        }
        .price{
          .label-s{
            display: none;
          }
        }
        .stock{
          display: none;
        }
        .info-bar{
          &.true{
            .buy-now-type{
              display: none!important;
            }
          }
          .remove-type.line-item{
            display: none!important;
          }
          .remove-type{
            display: block!important;
          }            
        }            
        .last-item{
          display: none!important;
        }
      }
    }
    &.show-type-4{
      li{
        display: -webkit-box;
        display: -webkit-flex;
        display: flex;
        flex-flow: row;
        align-items: center;
        padding: 10px 10px;
        &:last-child{
          margin-bottom: 0;
        }
        &:nth-child(even){
          .pic-box{
            &.even{
              display: none;
            }
            &.odd{
              display: block;
              margin-right: 0;
              margin-left: 14px;
            }                
          }
        }
        &:nth-child(odd){
          .pic-box{
            &.even{
              display: block;                
            }
            &.odd{
              display: none;
            }
          }
        }
        .desc{
          margin-bottom: 6px!important;
        }
        .pic-box{
          margin-right: 14px;              
          .gooods-pic{
            img{
              width: 122px;
              height: 122px;
            }
            &.pos-rel{
              &.del-show{
                .del-layer{
                  &.stock-none{
                    label{
                      margin-top: 26%;
                    }
                  }
                  label{
                    width: 50px;
                    height: 50px;
                    line-height: 50px;
                    margin-top: 20%;
                    font-size: 13px;
                  }
                  p{
                    font-size: 10px;
                    margin-top: 5%;
                  }
                }
              }
            }
          }
        }
        .detail-box{
          -webkit-box-flex: 1;
          -webkit-flex: 1;
          flex: 1;
          padding: 0px!important;
        }
        .desc{
          margin-bottom: 13px;
        }
        .tag{
          margin-top: -1px;
          margin-bottom: -2px;
          span{
            padding: 1px 5px!important;
          }
        }
        .price{
          .flex-item{
            .label-f{
              display: flex;
              flex-flow: row;
              align-items: center;
              margin-left: 0;
            }
            .tag-xs-t{
              color: #292929;
              display: inline-block;
              vertical-align: bottom;
              margin-bottom: -2px;
            }
            .label-s{
              display: -webkit-box;
              display: -webkit-flex;
              display: flex;
              margin-top: -6px;
              margin-left: -2px;
            }
          }
        }
        .stock{
          display: none;
        }
        .info-bar{
          .remove-type{
            display: none!important;
          }
          .buy-now-type{
            display: none!important;
          }
        }            
        .last-item{
          display: inline-block!important;
          margin-top: 5px;
        }
      }
    }
    li{
      list-style-type: none;
      border-radius: 4px;
      box-shadow: 0 4px 9px rgba(133, 133, 133, 0.2);
      margin-bottom: 13px;        
      .detail-box{
        padding: 12px;
      }
      .buy-now-type{
        background: #fed806!important;
        border: #fed806 1px solid!important;
        padding: 4px 9px;
        line-height: normal;
        color: #333!important;
        &:after{
          display: none;
        }
      }
      .remove-type{
        background: #292929!important;
        border: #292929 1px solid!important;
        padding: 4px 9px;
        line-height: normal;
        color: #fff!important;
        &:after{
          display: none;
        }
      }
      .pic-box{
        &.odd{
          display: none;
        }
      }
      .gooods-pic{
        &.pos-rel{
          &.del-show{
            .del-layer-bg{
              display: block;
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              background: rgba(0, 0, 0, 0.7);
              z-index: 10;
            }
            .del-layer{
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              z-index: 11;
              text-align: center;
              color: #fff;
              display: block;
              &.stock-none{
                label{
                  margin-top: 18%;
                }
              }
              label{
                width: 50px;
                height: 50px;
                line-height: 50px;
                margin-top: 15%;
                font-size: 13px;                  
                background: rgba(0, 0, 0, 0.7);
                border: rgba(255, 255, 255, 0.7) 1px solid;
                border-radius: 100px;            
                display: inline-block;
              }
              p{
                display: block;
                font-size: 10px;
                margin-top: 5%;
              }
            }
          }
        }
        img{
          display: block;
        }
      }        
      .desc{
        height: 37px;
        line-height: 1.3;
        overflow:hidden;
        color: #595959;
        text-overflow:ellipsis;
        display:-webkit-box;
        -webkit-line-clamp:2;
        -webkit-box-orient:vertical;
        word-break:break-word;
      }
      .line-item{
        display: none;
      }
      .last-item{
        display: none;
      }
      .info-bar{
        >button{
          margin-bottom: 3px;
        }
        .tag{
          line-height: 1.3;
          .label-f{
            background: #fed807;
            color: #333;
            padding: 2px 5px;
          }
          .label-s{
            background: #272727;
            color: #fff;
            padding: 2px 5px;
            min-width: 60px;
            box-sizing: border-box;
            span{
              color: #ffc81b;
              font-style: normal;
              &.income-label{
                padding: 0!important;
              }
            }
          }
        }
        .price{
          .tag-xs-t{
            display: none;
          }
          .label-f{
            color: #ff0000;
          }
          .label-s{
            color: #292929;
            text-decoration: line-through;
          }
        }
        .stock{
          color: #818181;
        }
        label{
          font-weight: normal;
        }
      }
    }
  }
}
</style>
